/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.dao.impl;

import com.legendshop.dao.impl.GenericDaoImpl;
import com.legendshop.dao.support.*;
import com.legendshop.oa.dao.ProjectDao;
import com.legendshop.oa.dao.TaskEstimateDao;
import com.legendshop.oa.dto.DailyLogQueryDto;
import com.legendshop.oa.dto.UserOverProjectTimeInputDto;
import com.legendshop.oa.model.TaskEstimate;
import com.legendshop.util.AppUtils;
import com.legendshop.dao.sql.ConfigCode;

import java.util.*;

/**
 * The Class TaskEstimateDaoImpl. 任务时间估计Dao实现类
 */

public class TaskEstimateDaoImpl extends GenericDaoImpl<TaskEstimate, Long> implements TaskEstimateDao {
	
	private ProjectDao projectDao;

	/**
	 * 根据商城获取任务时间估计列表
	 */
	public List<TaskEstimate> getTaskEstimate(String userName) {
		return this.queryByProperties(new EntityCriterion().eq("userName", userName));
	}

	/**
	 * 根据Id获取任务时间估计
	 */
	public TaskEstimate getTaskEstimate(Long id) {
		return getById(id);
	}
	
	/**
	 * 根据Id获取任务时间估计,没有reviewed过的才可以删除
	 */
	public TaskEstimate getUnReviewedTaskEstimate(Long taskEstimateId) {
		TaskEstimate entity = getByProperties(new EntityCriterion().eq("reviewed", 0).eq("id", taskEstimateId));
		return entity;
	}

	/**
	 * 删除任务时间估计
	 */
	public int deleteTaskEstimate(TaskEstimate taskEstimate) {
		int result = delete(taskEstimate);
		if(result > 0){
			projectDao.updateProjectWorkingTime(taskEstimate.getProjectId());
		}
		return result;
		
	}

	/**
	 * 更新任务时间估计
	 */
	public int updateTaskEstimate(TaskEstimate taskEstimate) {
		int result = update(taskEstimate);
		if(result > 0){
			projectDao.updateProjectWorkingTime(taskEstimate.getProjectId());
		}
		return result;
	}

	/**
	 * 查询任务时间估计列表
	 */
	public PageSupport getTaskEstimate(CriteriaQuery cq) {
		return queryPage(cq);
	}

	/**
	 * 根据任务来查找工时
	 */
	@Override
	public List<TaskEstimate> getTaskEstimateByTask(Long taskId) {
		return query("select * from ls_taskestimate where task_id = ?", TaskEstimate.class, taskId);
	}
	
	/**
	 * 根据日期来获取任务, 获取日期
	 */
	@Override
	public List<TaskEstimate> getTaskEstimateByDay(Date date, String userName) {
		return query("select * from ls_taskestimate where date = ? and user_name = ?", TaskEstimate.class, date, userName);
	}
	
	@Override
	public PageSupport<TaskEstimate> getTaskEstimateByDay(Date startDate, Date endDate, DailyLogQueryDto dailyLogQueryDto) {
		SimpleSqlQuery query = new SimpleSqlQuery(TaskEstimate.class, 20, dailyLogQueryDto.getCurPageNO());
		QueryMap map = new QueryMap();
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("userName", dailyLogQueryDto.getUserName());
		String querySql = ConfigCode.getInstance().getCode("oa.getTaskEstimateByDay", map);
		String sqlCount = ConfigCode.getInstance().getCode("oa.getTaskEstimateByDayCount", map);
		query.setParam(map.toArray());
		query.setQueryString(querySql);
		query.setAllCountString(sqlCount);

		return querySimplePage(query);
		
	}

	/**
	 * 保存任务时间估计
	 */
	public Long saveTaskEstimate(TaskEstimate taskEstimate) {
		if(taskEstimate.getConsumed() > 0){//必须要有数据
			//增加前缀
			taskEstimate.setWork(getTaskEstimatePrefix(taskEstimate.getProjectId(),taskEstimate.getTaskId()) + ":" + taskEstimate.getWork());
			Long id =  save(taskEstimate);
			projectDao.updateProjectWorkingTime(taskEstimate.getProjectId());
			return id;
		}
		return 0l;
	}

	
	/**
	 * 批量保存任务
	 */
	@Override
	public void saveTaskEstimate(List<TaskEstimate> entities) {
		 Set<Long> projectIds = new HashSet<Long>();
		if(AppUtils.isNotBlank(entities)){
			 List<TaskEstimate> toBeSaveEntity = new ArrayList<TaskEstimate>();
			 for (TaskEstimate taskEstimate : entities) {
				if(taskEstimate.getConsumed() != null && taskEstimate.getConsumed() > 0){
					toBeSaveEntity.add(taskEstimate);
				}
			}
			 
			//设置remark, 加上项目名称和任务名称
			for (TaskEstimate entity : toBeSaveEntity) {
				entity.setWork(getTaskEstimatePrefix(entity.getProjectId(),entity.getTaskId()) + ":" + entity.getWork());
			}
			save(toBeSaveEntity);
			for (TaskEstimate entity : toBeSaveEntity) {
				projectIds.add(entity.getProjectId());
			}
		}
		if(AppUtils.isNotBlank(projectIds)){
			for (Long projectId : projectIds) {
				projectDao.updateProjectWorkingTime(projectId);
			}
			
		}
	}
	
	/**
	 * 获取工时所对应的项目和任务
	 * @return
	 */
	private String getTaskEstimatePrefix(Long projectId, Long taskId){
//		String sql = "SELECT CONCAT(p.name,':', t.name) AS title FROM ls_project p, ls_task t WHERE t.project_id = p.id AND p.id = ? AND t.id = ?";
//		return get(sql, String.class, projectId, taskId);
		String sql = "SELECT p.name AS title FROM ls_project p WHERE p.id = ?";
		return get(sql, String.class, projectId);
	}

	/**
	 * 根据任务情况工时
	 */
	@Override
	public void deleteTaskEstimateByTask(Long taskId) {
		List<TaskEstimate> entities = query("select * from ls_taskestimate where task_id = ?", TaskEstimate.class, taskId);
		if(AppUtils.isNotBlank(entities)){
			 Set<Long> projectIds = new HashSet<Long>();
				if(AppUtils.isNotBlank(entities)){
					for (TaskEstimate entity : entities) {
						projectIds.add(entity.getProjectId());
					}
				}
				
				delete(entities);//要先删除记录,才能更新工时
				
				if(AppUtils.isNotBlank(projectIds)){
					for (Long projectId : projectIds) {
						projectDao.updateProjectWorkingTime(projectId);
					}
					
				}
			
		}
	}

	/**
	 * 获取已经评审过的日志
	 */
	@Override
	public List<TaskEstimate> getReviewedTaskEstimateByTask(Long taskId) {
		return this.queryByProperties(new EntityCriterion().eq("taskId", taskId).eq("reviewed", 1));
	}

	public void setProjectDao(ProjectDao projectDao) {
		this.projectDao = projectDao;
	}

	/**
	 * 根据任务查找
	 */
	@Override
	public PageSupport<TaskEstimate> getTaskEstimateByTask(Long taskId, String curPageNO) {
		CriteriaQuery query = new CriteriaQuery(TaskEstimate.class,curPageNO);
		query.setPageSize(5);
		query.eq("taskId", taskId);
		query.addDescOrder("id");
		return queryPage(query);
	}

	/**
	 * 按分页查找某个用户某天的日志
	 */
	@Override
	public PageSupport<TaskEstimate> getTaskEstimateByDay(Date date1, String userName1, String curPageNO) {
		CriteriaQuery query = new CriteriaQuery(TaskEstimate.class,curPageNO);
		query.setPageSize(5);
		query.eq("date", date1);
		query.eq("userName", userName1);
		query.addDescOrder("id");
		return queryPage(query);
	}

	/**
	 * 计算某个用户在一周或者一个月的工时
	 */
	@Override
	public Long getTaskEstimateHoursByUser(String userName, Date startDate, Date endDate) {
		return get("SELECT SUM(consumed) FROM ls_taskestimate WHERE user_name = ? AND DATE >= ? AND DATE < ?", Long.class, userName, startDate, endDate);
	}


	/**
	 *  审核某个用户在一周或者一个月的工时的状态
	 */
	@Override
	public Integer updateTaskEstimateHoursByUser(String userName, Date startDate, Date endDate) {
		return update("update ls_taskestimate set reviewed = 1  WHERE user_name = ? AND DATE >= ? AND DATE < ?", userName, startDate, endDate);
	}

	@Override
	public List<UserOverProjectTimeInputDto> isUserOverProjectTimeInput(String userName, Date startDate, Date endDate) {
		String sql = "SELECT t1.*,p1.max_hours_perweek as maxHoursPerweek FROM (SELECT p.id,p.name, SUM(t.consumed) AS total FROM ls_taskestimate t, ls_project p WHERE t.project_id = p.id AND t.user_name = ? AND t.DATE >= ? AND t.DATE < ?  GROUP BY p.id) t1, ls_project p1 " +
				"WHERE t1.id = p1.id AND   p1.max_hours_perweek IS NOT NULL AND t1.total > p1.max_hours_perweek";
		return query(sql, UserOverProjectTimeInputDto.class, userName,startDate,endDate);
	}


}
